package com.jiahe.video.runner;


import com.jiahe.video.config.StepConfig;
import com.jiahe.video.model.Camera;
import com.jiahe.video.service.ApiService;
import com.jiahe.video.service.AppService;
import com.jiahe.video.service.impl.AbsCommonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronExpression;
import org.springframework.scheduling.support.CronTrigger;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author author
 */
@Slf4j
//@Component
//@Order(value=1)
public class AppRunner_bak extends AbsCommonService implements CommandLineRunner {

    @Resource
    private ApiService apiService;
    @Resource
    private AppService appService;
    @Resource
    private ThreadPoolTaskScheduler scheduler;
    @Resource
    private StepConfig stepConfig;

    @Override
    public void run(String... args) throws Exception {
        // 初始化用户昵称
        apiService.nicknameInit();

        sendWeComMessage("-- 服务重启 --");
        List<Camera> cameraList = apiService.getCameraList();
        log.info("共获取到{}个摄像头",cameraList.size());

        for (Camera camera : cameraList) {
            if (camera.getVision()!=2) {
                //低频
                CompletableFuture.runAsync(() -> {
                    try {
                        System.out.println("任务创建: cameraId:" + camera.getId());
                        String cron = stepConfig.getLowCron();
                        if (!CronExpression.isValidExpression(cron)) {
                            log.error("cron 格式错误");
                            return ;
                        }
                        Runnable task = () -> {
                            appService.detectionOnce(camera);
                        };
                        scheduler.schedule(task, new CronTrigger(cron));
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error(e.getMessage());
                    }
                });
            }else{
                // 高频
                Thread.sleep(2000);
                appService.buildWorker(camera);
            }
            /*if (camera.getIsUpload()!=1) {
                continue;
            }
            Thread.sleep(2000);
            appService.buildWorker(camera);*/
        }
    }

}
